// 城市数据配置（2024年已公布数据）
const cityData = {
    beijing: { name: '北京', minWage: 2420, avgWage: 12183 },
    shanghai: { name: '上海', minWage: 2690, avgWage: 12183 },
    guangzhou: { name: '广州', minWage: 2300, avgWage: 10883 },
    shenzhen: { name: '深圳', minWage: 2360, avgWage: 11620 },
    hangzhou: { name: '杭州', minWage: 2280, avgWage: 10883 },
    nanjing: { name: '南京', minWage: 2280, avgWage: 10883 },
    suzhou: { name: '苏州', minWage: 2280, avgWage: 10883 },
    chengdu: { name: '成都', minWage: 1780, avgWage: 10883 },
    wuhan: { name: '武汉', minWage: 1800, avgWage: 10883 },
    xian: { name: '西安', minWage: 1950, avgWage: 10883 }
};

// 密码配置
const PASSWORD = '123456';

// 检测是否为移动设备
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);

// 奖金计数器
let bonusCounter = 0;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 设置默认日期
    const today = new Date();
    const oneYearAgo = new Date(today.getFullYear() - 1, today.getMonth(), today.getDate());
    
    document.getElementById('endDate').value = today.toISOString().split('T')[0];
    document.getElementById('startDate').value = oneYearAgo.toISOString().split('T')[0];
    
    // 绑定回车键事件
    document.getElementById('passwordInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            checkPassword();
        }
    });

    // 移动端优化：防止双击缩放
    if (isMobile) {
        let lastTouchEnd = 0;
        document.addEventListener('touchend', function (event) {
            const now = (new Date()).getTime();
            if (now - lastTouchEnd <= 300) {
                event.preventDefault();
            }
            lastTouchEnd = now;
        }, false);

        // 移动端输入框优化
        const inputs = document.querySelectorAll('input[type="number"], input[type="text"], input[type="date"]');
        inputs.forEach(input => {
            input.addEventListener('focus', function() {
                // 延迟滚动到输入框位置
                setTimeout(() => {
                    this.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }, 300);
            });
        });
    }

    // 初始化触摸事件
    initTouchEvents();
    
    // 初始化奖金动态表单
    initBonusForm();
});

// 初始化奖金动态表单
function initBonusForm() {
    // 清空容器
    const container = document.getElementById('bonusesContainer');
    container.innerHTML = '';
    bonusCounter = 0;
}

// 添加奖金行
function addBonusRow() {
    bonusCounter++;
    const container = document.getElementById('bonusesContainer');
    
    const bonusRow = document.createElement('div');
    bonusRow.className = 'bonus-row';
    bonusRow.dataset.bonusId = bonusCounter;
    
    bonusRow.innerHTML = `
        <div class="bonus-label">奖金/其他收入 ${bonusCounter}</div>
        <input type="number" class="bonus-input bonus-amount-input" placeholder="奖金/其他收入金额" step="0.01" min="0" onchange="calculateAverageSalary()">
        <button type="button" class="remove-bonus-btn" onclick="removeBonusRow(${bonusCounter})" title="删除此行"></button>
    `;
    
    container.appendChild(bonusRow);
    
    // 移动端优化：滚动到新添加的行
    if (isMobile) {
        setTimeout(() => {
            bonusRow.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }, 100);
    }
}

// 删除奖金行
function removeBonusRow(bonusId) {
    const bonusRow = document.querySelector(`[data-bonus-id="${bonusId}"]`);
    if (bonusRow) {
        // 添加删除动画
        bonusRow.style.opacity = '0';
        bonusRow.style.transform = 'translateX(-20px)';
        
        setTimeout(() => {
            bonusRow.remove();
            calculateAverageSalary();
        }, 200);
    }
}

// 清空所有奖金
function clearAllBonuses() {
    if (confirm('确定要清空所有奖金数据吗？')) {
        const container = document.getElementById('bonusesContainer');
        container.innerHTML = '';
        bonusCounter = 0;
        calculateAverageSalary();
    }
}

// 初始化触摸事件
function initTouchEvents() {
    // 为链接添加触摸反馈
    const links = document.querySelectorAll('.link');
    links.forEach(link => {
        link.addEventListener('touchstart', function() {
            this.style.opacity = '0.7';
        });
        link.addEventListener('touchend', function() {
            this.style.opacity = '1';
        });
    });

    // 为按钮添加触摸反馈
    const buttons = document.querySelectorAll('button');
    buttons.forEach(button => {
        button.addEventListener('touchstart', function() {
            this.style.transform = 'scale(0.95)';
        });
        button.addEventListener('touchend', function() {
            this.style.transform = 'scale(1)';
        });
    });
}

// 密码验证
function checkPassword() {
    const password = document.getElementById('passwordInput').value;
    const errorElement = document.getElementById('passwordError');
    
    if (password === PASSWORD) {
        document.getElementById('passwordScreen').style.display = 'none';
        document.getElementById('calculatorScreen').style.display = 'block';
        errorElement.textContent = '';
        errorElement.classList.remove('show');
    } else {
        errorElement.textContent = '密码错误，请重新输入';
        errorElement.classList.add('show');
        document.getElementById('passwordInput').value = '';
        document.getElementById('passwordInput').focus();
        
        // 移动端震动反馈（如果支持）
        if (isMobile && navigator.vibrate) {
            navigator.vibrate(200);
        }
    }
}

// 退出登录
function logout() {
    document.getElementById('passwordScreen').style.display = 'flex';
    document.getElementById('calculatorScreen').style.display = 'none';
    document.getElementById('passwordInput').value = '';
    document.getElementById('passwordError').textContent = '';
    document.getElementById('passwordError').classList.remove('show');
}

// 计算在职年数
function calculateYears() {
    const startDate = new Date(document.getElementById('startDate').value);
    const endDate = new Date(document.getElementById('endDate').value);
    
    if (startDate && endDate && startDate < endDate) {
        const timeDiff = endDate.getTime() - startDate.getTime();
        const daysDiff = timeDiff / (1000 * 3600 * 24);
        const yearsDiff = daysDiff / 365.25;
        
        document.getElementById('yearsOfService').textContent = yearsDiff.toFixed(2);
        
        // 计算N值（根据年数确定补偿倍数）
        let nValue = 0;
        if (yearsDiff < 0.5) {
            nValue = 0.5;
        } else if (yearsDiff < 1) {
            nValue = 1;
        } else if (yearsDiff < 1.5) {
            nValue = 1.5;
        } else if (yearsDiff < 2) {
            nValue = 2;
        } else if (yearsDiff < 2.5) {
            nValue = 2.5;
        } else if (yearsDiff < 3) {
            nValue = 3;
        } else {
            nValue = Math.ceil(yearsDiff);
        }
        
        document.getElementById('nValue').textContent = nValue;
        
        // 重新计算补偿方案
        calculateCompensation();
    }
}

// 更新城市数据
function updateCityData() {
    const citySelect = document.getElementById('citySelect');
    const selectedCity = citySelect.value;
    
    if (selectedCity && cityData[selectedCity]) {
        const city = cityData[selectedCity];
        document.getElementById('minWage').textContent = city.minWage.toLocaleString();
        document.getElementById('avgWage').textContent = city.avgWage.toLocaleString();
    } else {
        document.getElementById('minWage').textContent = '0';
        document.getElementById('avgWage').textContent = '0';
    }
}

// 计算平均工资
function calculateAverageSalary() {
    const salaryInputs = document.querySelectorAll('.salary-input');
    const bonusRows = document.querySelectorAll('.bonus-row');
    
    let totalSalary = 0;
    let validCount = 0;
    
    // 计算12个月工资总收入
    salaryInputs.forEach(input => {
        const salary = parseFloat(input.value) || 0;
        if (salary > 0) {
            totalSalary += salary;
            validCount++;
        }
    });
    
    // 计算奖金
    let totalBonus = 0;
    
    bonusRows.forEach(row => {
        const bonusInput = row.querySelector('.bonus-amount-input');
        const bonus = parseFloat(bonusInput?.value) || 0;
        totalBonus += bonus;
    });
    
    // 如果没有有效工资数据，返回0
    if (validCount === 0) {
        document.getElementById('monthlyAvgSalary').textContent = '0';
        document.getElementById('salaryBase').textContent = '0';
        document.getElementById('dailyWage').textContent = '0';
        calculateCompensation();
        return;
    }
    
    // 计算月平均工资（工资 + 奖金）
    let monthlyAvgSalary = (totalSalary + totalBonus) / validCount;
    
    // 获取当地月平均工资，用于3倍限制计算
    const citySelect = document.getElementById('citySelect');
    const selectedCity = citySelect.value;
    let localAvgWage = 0;
    
    if (selectedCity && cityData[selectedCity]) {
        localAvgWage = cityData[selectedCity].avgWage;
    }
    
    // 根据《劳动合同法实施条例》第二十七条规定，月平均工资不能超过当地上年度职工月平均工资的3倍
    if (localAvgWage > 0 && monthlyAvgSalary > localAvgWage * 3) {
        monthlyAvgSalary = localAvgWage * 3;
        // 显示提示信息
        showSalaryLimitNotice(localAvgWage * 3);
    } else {
        // 清除提示信息
        clearSalaryLimitNotice();
    }
    
    document.getElementById('monthlyAvgSalary').textContent = monthlyAvgSalary.toFixed(2);
    
    // 计算平均工资基数（直接使用月平均工资）
    const salaryBase = monthlyAvgSalary;
    document.getElementById('salaryBase').textContent = salaryBase.toFixed(2);
    
    // 计算日工资
    const dailyWage = salaryBase / 21.75;
    document.getElementById('dailyWage').textContent = dailyWage.toFixed(2);
    
    // 重新计算补偿方案
    calculateCompensation();
}

// 显示工资限制提示
function showSalaryLimitNotice(limitAmount) {
    let noticeElement = document.getElementById('salaryLimitNotice');
    if (!noticeElement) {
        noticeElement = document.createElement('div');
        noticeElement.id = 'salaryLimitNotice';
        noticeElement.className = 'salary-limit-notice';
        const salaryBaseElement = document.getElementById('salaryBase').parentElement;
        salaryBaseElement.appendChild(noticeElement);
    }
    
    noticeElement.innerHTML = `
        <div class="notice-content">
            <span class="notice-icon">⚠️</span>
            <span class="notice-text">
                根据《劳动合同法实施条例》第二十七条规定，月平均工资已超过当地上年度职工月平均工资的3倍（${limitAmount.toLocaleString()}元），已按3倍计算。
            </span>
        </div>
    `;
    noticeElement.style.display = 'block';
}

// 清除工资限制提示
function clearSalaryLimitNotice() {
    const noticeElement = document.getElementById('salaryLimitNotice');
    if (noticeElement) {
        noticeElement.style.display = 'none';
    }
}

// 计算补偿方案
function calculateCompensation() {
    const nValue = parseFloat(document.getElementById('nValue').textContent) || 0;
    const salaryBase = parseFloat(document.getElementById('salaryBase').textContent) || 0;
    
    // 协商解除 - 提前1个月通知
    const negotiated1Month = nValue * salaryBase;
    document.getElementById('negotiated1Month').textContent = negotiated1Month.toFixed(2);
    
    // 协商解除 - 当天通知（N+1：N个月的月平均工资 + 1个月的月工资）
    const negotiatedSameDay = (nValue * salaryBase) + salaryBase;
    document.getElementById('negotiatedSameDay').textContent = negotiatedSameDay.toFixed(2);
    
    // 违法解除
    const illegalTermination = 2 * nValue * salaryBase;
    document.getElementById('illegalTermination').textContent = illegalTermination.toFixed(2);
}

// 计算年假和加班费
function calculateLeaveAndOvertime() {
    const dailyWage = parseFloat(document.getElementById('dailyWage').textContent) || 0;
    const remainingLeave = parseFloat(document.getElementById('remainingLeave').value) || 0;
    const weekendOvertime = parseFloat(document.getElementById('weekendOvertime').value) || 0;
    const holidayOvertime = parseFloat(document.getElementById('holidayOvertime').value) || 0;
    
    // 年假折算金额（按日工资的3倍计算）
    const leaveAmount = remainingLeave * dailyWage * 3;
    document.getElementById('leaveAmount').textContent = leaveAmount.toFixed(2);
    
    // 加班费金额（周末按2倍，节假日按3倍）
    const weekendOvertimeAmount = weekendOvertime * dailyWage * 2;
    const holidayOvertimeAmount = holidayOvertime * dailyWage * 3;
    const totalOvertimeAmount = weekendOvertimeAmount + holidayOvertimeAmount;
    document.getElementById('overtimeAmount').textContent = totalOvertimeAmount.toFixed(2);
}

// 打开最低工资查询链接
function openMinWageQuery() {
    const citySelect = document.getElementById('citySelect');
    const selectedCity = citySelect.value;
    
    if (selectedCity) {
        const cityName = cityData[selectedCity]?.name || '';
        const url = `https://www.baidu.com/s?wd=${encodeURIComponent(cityName + '最低工资标准2024')}`;
        
        // 移动端优化：使用新窗口打开
        if (isMobile) {
            window.open(url, '_blank', 'noopener,noreferrer');
        } else {
            window.open(url, '_blank');
        }
    } else {
        showMobileAlert('请先选择城市');
    }
}

// 打开平均工资查询链接
function openAvgWageQuery() {
    const citySelect = document.getElementById('citySelect');
    const selectedCity = citySelect.value;
    
    if (selectedCity) {
        const cityName = cityData[selectedCity]?.name || '';
        const url = `https://www.baidu.com/s?wd=${encodeURIComponent(cityName + '平均工资2024')}`;
        
        // 移动端优化：使用新窗口打开
        if (isMobile) {
            window.open(url, '_blank', 'noopener,noreferrer');
        } else {
            window.open(url, '_blank');
        }
    } else {
        showMobileAlert('请先选择城市');
    }
}

// 移动端友好的提示
function showMobileAlert(message) {
    if (isMobile) {
        // 创建自定义提示框
        const alertBox = document.createElement('div');
        alertBox.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 15px 20px;
            border-radius: 8px;
            z-index: 10000;
            font-size: 14px;
            max-width: 80%;
            text-align: center;
        `;
        alertBox.textContent = message;
        document.body.appendChild(alertBox);
        
        setTimeout(() => {
            document.body.removeChild(alertBox);
        }, 2000);
    } else {
        alert(message);
    }
}

// 格式化数字显示
function formatNumber(num) {
    return num.toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
}

// 数据验证
function validateInput(input) {
    const value = parseFloat(input.value);
    if (value < 0) {
        input.value = 0;
    }
}

// 绑定输入验证事件
document.addEventListener('DOMContentLoaded', function() {
    const numberInputs = document.querySelectorAll('input[type="number"]');
    numberInputs.forEach(input => {
        input.addEventListener('blur', function() {
            validateInput(this);
        });
        
        // 移动端优化：防止输入框缩放
        if (isMobile) {
            input.addEventListener('focus', function() {
                this.style.fontSize = '16px';
            });
            input.addEventListener('blur', function() {
                this.style.fontSize = '';
            });
        }
    });
});

// 自动保存功能（可选）
function saveData() {
    const bonusData = [];
    const bonusRows = document.querySelectorAll('.bonus-row');
    
    bonusRows.forEach(row => {
        const bonusInput = row.querySelector('.bonus-amount-input');
        bonusData.push({
            bonus: bonusInput?.value || ''
        });
    });
    
    const data = {
        startDate: document.getElementById('startDate').value,
        endDate: document.getElementById('endDate').value,
        city: document.getElementById('citySelect').value,
        bonusData: bonusData,
        remainingLeave: document.getElementById('remainingLeave').value,
        weekendOvertime: document.getElementById('weekendOvertime').value,
        holidayOvertime: document.getElementById('holidayOvertime').value,
        unpaidWages: document.getElementById('unpaidWages').value,
        unreimbursedExpenses: document.getElementById('unreimbursedExpenses').value,
        socialSecurity: document.getElementById('socialSecurity').value
    };
    
    localStorage.setItem('calculatorData', JSON.stringify(data));
}

// 加载保存的数据
function loadData() {
    const savedData = localStorage.getItem('calculatorData');
    if (savedData) {
        const data = JSON.parse(savedData);
        
        if (data.startDate) document.getElementById('startDate').value = data.startDate;
        if (data.endDate) document.getElementById('endDate').value = data.endDate;
        if (data.city) {
            document.getElementById('citySelect').value = data.city;
            updateCityData();
        }
        if (data.remainingLeave) document.getElementById('remainingLeave').value = data.remainingLeave;
        if (data.weekendOvertime) document.getElementById('weekendOvertime').value = data.weekendOvertime;
        if (data.holidayOvertime) document.getElementById('holidayOvertime').value = data.holidayOvertime;
        if (data.unpaidWages) document.getElementById('unpaidWages').value = data.unpaidWages;
        if (data.unreimbursedExpenses) document.getElementById('unreimbursedExpenses').value = data.unreimbursedExpenses;
        if (data.socialSecurity) document.getElementById('socialSecurity').value = data.socialSecurity;
        
        // 加载奖金数据
        if (data.bonusData && data.bonusData.length > 0) {
            // 清空现有奖金
            const container = document.getElementById('bonusesContainer');
            container.innerHTML = '';
            bonusCounter = 0;
            
            // 重新添加奖金数据
            data.bonusData.forEach(bonusData => {
                addBonusRow();
                const lastRow = container.lastElementChild;
                if (lastRow) {
                    const bonusInput = lastRow.querySelector('.bonus-amount-input');
                    if (bonusInput) bonusInput.value = bonusData.bonus || '';
                }
            });
        }
        
        // 重新计算
        calculateYears();
        calculateAverageSalary();
        calculateLeaveAndOvertime();
    }
}

// 页面加载时加载保存的数据
document.addEventListener('DOMContentLoaded', function() {
    // 延迟加载，确保密码验证通过后再加载
    setTimeout(loadData, 100);
});

// 定期自动保存
setInterval(saveData, 30000); // 每30秒保存一次

// 移动端滚动优化
if (isMobile) {
    // 平滑滚动
    document.documentElement.style.scrollBehavior = 'smooth';
    
    // 防止橡皮筋效果
    document.body.style.overscrollBehavior = 'none';
    
    // 优化触摸滚动
    const sections = document.querySelectorAll('.section');
    sections.forEach(section => {
        section.style.touchAction = 'pan-y';
    });
} 

// 展开折叠法律详情
function toggleLegalDetail(articleId) {
    const content = document.getElementById(articleId);
    const legalItem = content.previousElementSibling;
    const legalIcon = legalItem.querySelector('.legal-icon');
    
    if (content.style.display === 'none') {
        // 展开
        content.style.display = 'block';
        legalItem.classList.add('expanded');
        legalIcon.textContent = '▲';
    } else {
        // 折叠
        content.style.display = 'none';
        legalItem.classList.remove('expanded');
        // legalIcon.textContent = '▼';
    }
} 